package com.security.service;

import com.common.result.Result;
import com.common.util.StringUtil;
import lombok.Builder;
import lombok.Data;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 负责与认证中心通信的service
 *
 * @author 大忽悠
 * @create 2022/10/11 20:51
 */
@Data
public class AuthenticateService {
    private final RestTemplate restTemplate = new RestTemplate();
    private String authenticateCenterUrl;

    /**
     * @param id   用户id
     * @param name 用户姓名
     * @return token
     */
    public Result generatorToken(Integer id, String name) {
        MultiValueMap<String, Object> request = new LinkedMultiValueMap<>();
        request.add("id", id);
        request.add("name", name);
        return restTemplate.postForObject(authenticateCenterUrl + "/authenticateCenter/authenticate/token", request, Result.class);
    }

    /**
     * @param token
     * @return 如果token认证成功, 返回UserDetails, 并且响应头中返回了刷新后的token, 解析失败返回null
     */
    public Result verifyToken(String token) {
        MultiValueMap<String, Object> request = new LinkedMultiValueMap<>();
        request.add("token", token);
        return restTemplate.postForObject(authenticateCenterUrl + "/authenticateCenter/authenticate/verify", request, Result.class);
    }

    /**
     * @param url 用户请求url
     * @return 访问当前请求需要具备哪些角色
     */
    public Result getRolesOfRequestUrl(String url) {
        MultiValueMap<String, Object> request = new LinkedMultiValueMap<>();
        request.add("url", url);
        return restTemplate.postForObject(authenticateCenterUrl + "/authenticateCenter/authenticate/listRolesOfRequestUrl", request, Result.class);
    }

    /**
     * 向注册中心同步新注册的用户信息,默认不同步密码
     *
     * @param username
     * @param password
     */
    public void addUser(String username, String password, String... roleList) {
        Result result = restTemplate.postForObject(authenticateCenterUrl + "/authenticateCenter/user/add", UserForJson.builder()
                .username(username).password(null).build(), Result.class);
        //为用户赋予角色
        Integer userId = (Integer) result.getData();
        MultiValueMap requestParams = new LinkedMultiValueMap();
        requestParams.add("uid", userId);
        requestParams.add("roleNameList", String.join(StringUtil.DELIMITER, roleList));
        restTemplate.postForObject(authenticateCenterUrl + "/authenticateCenter/role/releaseByNameList", requestParams, Result.class);
    }

    @Builder
    @Data
    private static class UserForJson {
        private String username;
        private String password;
    }
}
